package com.veryUsedCar.service.impl;

import com.veryUsedCar.VO.NewsVO;
import com.veryUsedCar.service.NewsService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void saveNews(NewsVO news) {
        if (!redisTemplate.hasKey("msgkey")){ //如果没有该数据库就创建这个数据库将数据放入 如果有就将该数据放入数据库种
//            val newskey = redisTemplate.boundHashOps("msgk");
            //增加数据 并设置有效时间
            redisTemplate.boundHashOps("msgkey").put(UUID.randomUUID(),news);
            redisTemplate.boundHashOps("msgkey").expire(1, TimeUnit.MINUTES);
        }else{
            //如果数据库已将存在 就直接加入数据
            val newskey = redisTemplate.boundHashOps("msgkey");
            newskey.put(UUID.randomUUID(),news);
            newskey.expire(1, TimeUnit.MINUTES);
        }
    }

    @Override
    public void listNews() {
        if (redisTemplate.hasKey("msgkey")){
            redisTemplate.boundHashOps("msgkey").keys();
        }
    }

    @Override
    public int deleteNews(Long newsId) {
        val newskey = redisTemplate.boundHashOps("msgkey");
        if (redisTemplate.hasKey(newskey)){
            newskey.delete(newsId);
            return 1;
        }else {
            return 0;
        }
    }
}
